#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/time.h>
#include "../../src/thread.h"


static void * pthreadfunc(void * arg){
  char *name = arg;
  printf("je suis le thread %p, lancé avec l'argument %s\n",
	 (void*) pthread_self(), name);
  pthread_exit(arg);
}

static void * threadfunc(void * arg){
  char *name = arg;
  printf("je suis le thread %d, lancé avec l'argument %s\n",
	 thread_self(), name);
  thread_exit(arg);
}

double getTime(){
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return 1000*tv.tv_sec+tv.tv_usec/1000.0;
}

int main(){
  double t0,t1,t2,t3;
  //les deux threads et leurs valeurs de retour
  pthread_t pth;
  thread_t th;
  void *pretval,*retval;
  int err;
  
  printf("le main lance 2 threads...\n");
  err = pthread_create(&pth, NULL, pthreadfunc, "pth");
  assert(!err);
  err = thread_create(&th, threadfunc,"th");
  assert(!err);
  printf("le main a lancé les threads %p and %d\n",(void*)pth,th);
  printf("le main attend les threads\n");

  t0 = getTime();
  err = pthread_join(pth, &pretval);
  assert(!err);
  t1 = getTime();
  printf("Coût de la destruction avec pthread :  %g\n",t1-t0);

  t2 = getTime();
  err = thread_join(th, &retval);
  assert(!err);
  t3 = getTime();
  printf("Coût de la destruction avec thread :  %g\n",t3-t2);
  
  printf("les threads ont terminé en renvoyant '%s' and '%s'\n",(char *)pretval, (char *) retval);
  return EXIT_SUCCESS;
}
